package com.yf.ability.upload.providers.cos.service.impl;

import com.alibaba.fastjson.JSON;
import com.tencent.cloud.CosStsClient;
import com.tencent.cloud.Credentials;
import com.tencent.cloud.Response;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.yf.ability.config.dto.CfgPropDTO;
import com.yf.ability.config.enums.ConfigType;
import com.yf.ability.config.enums.ProviderType;
import com.yf.ability.config.service.CfgPropService;
import com.yf.base.api.exception.ServiceException;
import com.yf.ability.upload.providers.cos.config.CosConfig;
import com.yf.ability.upload.providers.cos.dto.CosTokenDTO;
import com.yf.ability.upload.providers.cos.service.CosService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.util.TreeMap;

@Service
public class CosServiceImpl implements CosService {

    @Autowired
    private CfgPropService cfgPropService;

    @Override
    public CosTokenDTO token() {
        // 获得上传配置
        CosConfig conf = this.getConfig();
        TreeMap<String, Object> config = new TreeMap<>();

        try {
            // 替换为您的 SecretId
            config.put("SecretId", conf.getSecretId());
            // 替换为您的 SecretKey
            config.put("SecretKey", conf.getSecretKey());
            // 临时密钥有效时长，单位是秒，默认1800秒，目前主账号最长2小时（即7200秒），子账号最长36小时（即129600秒）
            config.put("durationSeconds", 1800);
            // 换成您的 bucket
            config.put("bucket", conf.getBucket());
            // 换成 bucket 所在地区
            config.put("region", conf.getRegion());
            // 这里改成允许的路径前缀，可以根据自己网站的用户登录态判断允许上传的具体路径，例子：a.jpg 或者 a/* 或者 * 。
            // 如果填写了“*”，将允许用户访问所有资源；除非业务需要，否则请按照最小权限原则授予用户相应的访问权限范围。
            config.put("allowPrefix", "*");
            // 简单上传、表单上传和分片上传需要以下的权
            String[] allowActions = new String[] {
                    // 简单上传
                    "name/cos:PutObject",
                    // 表单上传、小程序上传
                    "name/cos:PostObject",
                    // 分片上传
                    "name/cos:InitiateMultipartUpload",
                    "name/cos:ListMultipartUploads",
                    "name/cos:ListParts",
                    "name/cos:UploadPart",
                    "name/cos:CompleteMultipartUpload"
            };
            config.put("allowActions", allowActions);
            Response resp = CosStsClient.getCredential(config);
            return this.buildRest(resp.credentials, conf);
        } catch (Exception e) {
            throw new ServiceException("构建上传token失败："+e.getMessage());
        }
    }

    @Override
    public CosConfig getConfig(){
        CfgPropDTO dto = cfgPropService.detail(ConfigType.UPLOAD, ProviderType.QCLOUD);
        CosConfig cfg = JSON.parseObject(dto.getData(), CosConfig.class);
        return cfg;
    }

    @Override
    public String convertVideo(String input) {

        // TODO 实现媒体转换
        return input;
    }

    /**
     * 构建返回响应
     * @param data
     * @param conf
     * @return
     */
    private CosTokenDTO buildRest(Credentials data, CosConfig conf){

        CosTokenDTO respDTO = new CosTokenDTO();
        respDTO.setSessionToken(data.sessionToken);
        respDTO.setTmpSecretId(data.tmpSecretId);
        respDTO.setTmpSecretKey(data.tmpSecretKey);
        respDTO.setHost(MessageFormat.format("https://{0}.cos.{1}.myqcloud.com/", conf.getBucket(), conf.getRegion()));
        respDTO.setUrl(conf.getUrl());
        respDTO.setBucket(conf.getBucket());
        respDTO.setRegion(conf.getRegion());

        return respDTO;
    }
}
